package org.tangolyricstagger.gui;

import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Appender;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.Level;
import org.apache.log4j.spi.LoggingEvent;
import org.apache.log4j.spi.ThrowableInformation;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Display;

public class GuiAppender extends AppenderSkeleton implements Appender {

	private final Color yellow = Display.getCurrent().getSystemColor(SWT.COLOR_YELLOW);
	private final Color red = Display.getCurrent().getSystemColor(SWT.COLOR_RED);

	private StyledText text;

	public GuiAppender(StyledText text) {
		super();
		this.text = text;
	}

	@Override
	public void close() {
		// TODO Auto-generated method stub
	}

	@Override
	public boolean requiresLayout() {
		return true;
	}

	@Override
	protected void append(final LoggingEvent event) {
		Display.getDefault().asyncExec(new Runnable() {
			public void run() {
				String message = ObjectUtils.toString(event.getMessage());
				int lineCount = text.getLineCount();
				text.append(message + "\n");
				// text.setTopIndex(lineCount - 1);

				if (event.getLevel().equals(Level.WARN)) {
					text.setLineBackground(lineCount - 1, text.getLineCount() - lineCount, yellow);
				}
				if (event.getLevel().equals(Level.ERROR)) {
					ThrowableInformation throwableInformation = event.getThrowableInformation();
					if (throwableInformation != null) {
						String[] throwableStrRep = event.getThrowableInformation().getThrowableStrRep();
						text.append(StringUtils.join(throwableStrRep, "\n"));
					}
					text.setLineBackground(lineCount - 1, text.getLineCount() - lineCount, red);
				}
			}
		});
	}

}
